import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Search, Filter, BookOpen, Users, Clock, Target } from "lucide-react";

interface PBLCase {
  id: string;
  title: string;
  description: string;
  subject: string;
  grade: string;
  duration: string;
  participants: number;
  difficulty: string;
  tags: string[];
}

const mockCases: PBLCase[] = [
  {
    id: "1",
    title: "Environmental Protection Campaign",
    description: "Students research local environmental issues and develop action plans to raise awareness in their community.",
    subject: "Science",
    grade: "9-12",
    duration: "4 weeks",
    participants: 24,
    difficulty: "Intermediate",
    tags: ["Environment", "Research", "Campaign", "Community"]
  },
  {
    id: "2",
    title: "Community Garden Design",
    description: "Interdisciplinary project where students design a community garden, integrating math, science, and social studies.",
    subject: "STEM",
    grade: "6-8",
    duration: "6 weeks",
    participants: 18,
    difficulty: "Advanced",
    tags: ["Garden", "Design", "Math", "Science", "Community"]
  },
  {
    id: "3",
    title: "Historical Documentary Creation",
    description: "Students create documentary films about local history, developing research and digital media skills.",
    subject: "History",
    grade: "7-12",
    duration: "8 weeks",
    participants: 20,
    difficulty: "Advanced",
    tags: ["History", "Documentary", "Media", "Research"]
  },
  {
    id: "4",
    title: "Small Business Plan Development",
    description: "Students develop comprehensive business plans for solving local community problems through entrepreneurship.",
    subject: "Business",
    grade: "10-12",
    duration: "5 weeks",
    participants: 16,
    difficulty: "Intermediate",
    tags: ["Business", "Entrepreneurship", "Planning", "Community"]
  }
];

const subjects = ["All", "Science", "STEM", "History", "Business", "Math", "Language Arts"];
const difficulties = ["All", "Beginner", "Intermediate", "Advanced"];

interface PBLCaseWorkshopProps {
  simpleListMode?: boolean;
}

export function PBLCaseWorkshop({ simpleListMode }: PBLCaseWorkshopProps = {}) {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedSubject, setSelectedSubject] = useState("All");
  const [selectedDifficulty, setSelectedDifficulty] = useState("All");
  const [filteredCases, setFilteredCases] = useState(mockCases);

  const filterCases = (search: string, subject: string, difficulty: string) => {
    let filtered = mockCases;

    if (subject !== "All") {
      filtered = filtered.filter(case_ => case_.subject === subject);
    }

    if (difficulty !== "All") {
      filtered = filtered.filter(case_ => case_.difficulty === difficulty);
    }

    if (search) {
      filtered = filtered.filter(case_ => 
        case_.title.toLowerCase().includes(search.toLowerCase()) ||
        case_.description.toLowerCase().includes(search.toLowerCase()) ||
        case_.tags.some(tag => tag.toLowerCase().includes(search.toLowerCase()))
      );
    }

    setFilteredCases(filtered);
  };

  const handleSearch = (term: string) => {
    setSearchTerm(term);
    filterCases(term, selectedSubject, selectedDifficulty);
  };

  const handleSubjectFilter = (subject: string) => {
    setSelectedSubject(subject);
    filterCases(searchTerm, subject, selectedDifficulty);
  };

  const handleDifficultyFilter = (difficulty: string) => {
    setSelectedDifficulty(difficulty);
    filterCases(searchTerm, selectedSubject, difficulty);
  };

  if (simpleListMode) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-4">
        {mockCases.map((case_) => (
          <Card key={case_.id} className="h-full hover:shadow-lg transition-shadow duration-200">
            <CardHeader>
              <div className="flex items-start justify-between mb-2">
                <Badge variant="secondary" className="text-xs">
                  {case_.subject}
                </Badge>
                <Badge 
                  className={`text-xs ${
                    case_.difficulty === 'Beginner' ? 'bg-green-100 text-green-700' :
                    case_.difficulty === 'Intermediate' ? 'bg-yellow-100 text-yellow-700' :
                    'bg-red-100 text-red-700'
                  }`}
                >
                  {case_.difficulty}
                </Badge>
              </div>
              <CardTitle className="text-lg font-semibold line-clamp-2">
                {case_.title}
              </CardTitle>
              <CardDescription className="line-clamp-3">
                {case_.description}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex flex-wrap gap-2">
                {case_.tags.map((tag) => (
                  <Badge key={tag} variant="outline" className="text-xs">
                    {tag}
                  </Badge>
                ))}
              </div>
              <div className="flex justify-between text-xs text-gray-500">
                <span>Grade: {case_.grade}</span>
                <span>Duration: {case_.duration}</span>
                <span>Participants: {case_.participants}</span>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="space-y-4">
        <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
          <h2 className="text-2xl font-bold text-gray-900">PBL Case Workshop</h2>
          <Badge variant="secondary" className="bg-blue-100 text-blue-700">
            {filteredCases.length} Cases Available
          </Badge>
        </div>
        
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
          <Input
            placeholder="Search PBL cases..."
            value={searchTerm}
            onChange={(e) => handleSearch(e.target.value)}
            className="pl-10 h-12 text-base"
          />
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="flex items-center gap-2">
          <Filter className="w-4 h-4 text-muted-foreground" />
          <span className="text-sm font-medium">Subject:</span>
          <Select value={selectedSubject} onValueChange={handleSubjectFilter}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {subjects.map((subject) => (
                <SelectItem key={subject} value={subject}>
                  {subject}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium">Difficulty:</span>
          <Select value={selectedDifficulty} onValueChange={handleDifficultyFilter}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {difficulties.map((difficulty) => (
                <SelectItem key={difficulty} value={difficulty}>
                  {difficulty}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Cases Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {filteredCases.map((case_) => (
          <Card key={case_.id} className="h-full hover:shadow-lg transition-shadow duration-200">
            <CardHeader>
              <div className="flex items-start justify-between mb-2">
                <Badge variant="secondary" className="text-xs">
                  {case_.subject}
                </Badge>
                <Badge 
                  className={`text-xs ${
                    case_.difficulty === 'Beginner' ? 'bg-green-100 text-green-700' :
                    case_.difficulty === 'Intermediate' ? 'bg-yellow-100 text-yellow-700' :
                    'bg-red-100 text-red-700'
                  }`}
                >
                  {case_.difficulty}
                </Badge>
              </div>
              <CardTitle className="text-lg font-semibold line-clamp-2">
                {case_.title}
              </CardTitle>
              <CardDescription className="line-clamp-3">
                {case_.description}
              </CardDescription>
            </CardHeader>
            
            <CardContent className="space-y-4">
              <div className="flex flex-wrap gap-1">
                {case_.tags.map((tag) => (
                  <Badge key={tag} variant="outline" className="text-xs">
                    {tag}
                  </Badge>
                ))}
              </div>
              
              <div className="grid grid-cols-2 gap-4 text-sm text-muted-foreground">
                <div className="flex items-center gap-1">
                  <BookOpen className="w-4 h-4" />
                  <span>Grade {case_.grade}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Clock className="w-4 h-4" />
                  <span>{case_.duration}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Users className="w-4 h-4" />
                  <span>{case_.participants} students</span>
                </div>
                <div className="flex items-center gap-1">
                  <Target className="w-4 h-4" />
                  <span>{case_.subject}</span>
                </div>
              </div>
              
              <div className="flex gap-2 pt-2">
                <Button variant="outline" size="sm" className="flex-1">
                  Preview
                </Button>
                <Button size="sm" className="flex-1">
                  Use Case
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredCases.length === 0 && (
        <div className="text-center py-12">
          <p className="text-muted-foreground mb-4">No matching PBL cases found</p>
          <Button 
            variant="outline" 
            onClick={() => {
              setSearchTerm("");
              setSelectedSubject("All");
              setSelectedDifficulty("All");
              setFilteredCases(mockCases);
            }}
          >
            Clear Filters
          </Button>
        </div>
      )}
    </div>
  );
}
